let AudioManager = module.exports = {};

//0为静音，1为开启声音
AudioManager.init = function () {
    this.currentBgMusic = -1;
    //初始化音乐和音效的音量
    if (!cc.sys.localStorage.getItem('MusicVolume')) {
        this.musicVolume = 1;
        this.soundVolume = 1;
        cc.sys.localStorage.setItem('MusicVolume', this.musicVolume.toString());
        cc.sys.localStorage.setItem('SoundVolume', this.soundVolume.toString());
    } else {
        this.musicVolume = parseFloat(cc.sys.localStorage.getItem('MusicVolume'));
        this.soundVolume = parseFloat(cc.sys.localStorage.getItem('SoundVolume'));
    }
};

AudioManager.getUrl = function(url,callback){
    return cc.resources.load("sounds/" + url,function(err, assets){
        callback(assets);
     })
};

AudioManager.startPlayBgMusic = function (url) {
    var self = this;
    if (!url) {
        cc.error("startPlayBgMusic", "url:" + url);
        return;
    }
    AudioManager.stopBgMusic();
    var callback = function(assets){
        if(self.musicVolume > 0){
            self.currentBgMusic = cc.audioEngine.play(assets,true,self.musicVolume);
        }
    }
    self.getUrl(url,callback);
};

AudioManager.stopBgMusic = function () {
    if (this.currentBgMusic < 0) return;
    cc.audioEngine.stop(this.currentBgMusic);
    this.currentBgMusic = -1;
};

AudioManager.playSound = function (url='button', loop) {
    if (!this.soundVolume) return;
    if (!loop) loop = false;
    var self = this;
    var callback = function(assets){
        if(self.soundVolume > 0){
            cc.audioEngine.play(assets,loop,self.soundVolume);
        }
    }
    self.getUrl(url,callback);
};

AudioManager.setMusicVolume = function (volume) {
    this.musicVolume = parseFloat(volume.toFixed(1));
    cc.sys.localStorage.setItem('MusicVolume', this.musicVolume);

    if (volume === 0) {
        cc.audioEngine.pause(this.currentBgMusic);
    } else {
        if (this.currentBgMusic >= 0) {
            cc.audioEngine.setVolume(this.currentBgMusic, this.musicVolume);
        }
    }
};

AudioManager.getMusicVolume = function () {
    return this.musicVolume;
};

AudioManager.setSoundVolume = function (volume) {
    this.soundVolume = parseFloat(volume.toFixed(1));
    cc.sys.localStorage.setItem('SoundVolume', this.soundVolume);
};

AudioManager.getSoundVolume = function () {
    return this.soundVolume;
};
AudioManager.pauseAll = function () {
    cc.audioEngine.pauseAll();
};

AudioManager.resumeAll = function () {
    cc.audioEngine.resumeAll();
};
